<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right" class="el-breadcrumb">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>


        <!-- 卡片视图 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <div>
                        <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query">
                            <el-button slot="append" @click="getUserListInfo" icon="el-icon-search"></el-button>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addUserInfo">新增用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data='userList'>
                <el-table-column type='index' />
                <el-table-column prop="username" label="姓名" width="180" />
                <el-table-column prop="email" label="邮箱" width="180" />
                <el-table-column prop="mobile" label="电话" width="180" />
                <el-table-column prop="role_name" label="角色" width="180" />
                <el-table-column label="状态" width="180">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"
                            active-color="#13ce66" inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button @click="editUserInfo(scope.row.id)" type="primary" icon="el-icon-edit" size="mini">
                        </el-button>
                        <el-button type="primary" icon="el-icon-delete" size="mini"
                            @click="removeUserbyId(scope.row.id)"></el-button>
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum" :page-sizes="[1, 5, 10, 20]" :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper" :total="this.total">
                </el-pagination>
            </div>
        </el-card>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="adddialogvisable" width="30%" :modal-append-to-body="false"
            @close="addDialogClose">
            <!-- 内容主体区 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="adddialogvisable = false">取 消</el-button>
                <el-button type="primary" @click="adddUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户信息对话框 -->
        <el-dialog title="修改用户" :visible.sync="editdialogvisable" width="50%" :modal-append-to-body="false"
            @close="editDialogClose">
            <!-- 内容主体区 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <!-- <el-form-item label="id" prop="username">
                    <el-input v-model="editForm.id"></el-input>
                </el-form-item> -->
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" :disabled="true"></el-input>
                </el-form-item>
                <!-- <el-form-item label="密码" prop="password">
                    <el-input v-model="editForm.password"></el-input>
                </el-form-item> -->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="adddialogvisable = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>


<script>
export default {
    data() {
        var checkEmail = (rule, value, callback) => {
            if (/^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value) == false) {
                callback(new Error("请输入正确的邮箱"));
            } else {
                //校验通过
                callback();
            }
        }
        var checkMobile = (rule, value, callback) => {
            if (/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
            } else {
                //校验通过
                callback();
            }
        }
        return {
            userList: [],
            total: null,
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 2
            },
            adddialogvisable: false,
            addForm: {
                username: null,
                password: null,
                email: null,
                mobile: null
            },
            editdialogvisable: false,
            editForm: {
                username: null,
                password: null,
                email: null,
                mobile: null
            },
            addFormRules: {
                username: [{ required: 'true', trigger: 'blur', message: '用户名不能为空' },
                { min: 3, max: 10, message: '用户名的长度在3-10之间' }],
                password: [{ required: 'true', trigger: 'blur', message: '密码不能为空' },
                { min: 6, max: 15, message: '密码要在6-15位之间' }],
                email: [
                    { required: true, message: "请输入邮箱", trigger: "blur" },
                    {
                        validator: checkEmail
                    }
                ],
                mobile: [{ required: 'true', trigger: 'blur', message: '手机号不能为空' }
                    , { validator: checkMobile, trigger: 'blur' }]
            },
            editFormRules: {
                email: [
                    { required: true, message: "请输入邮箱", trigger: "blur" },
                    { validator: checkEmail }
                ],
                mobile: [{ required: 'true', trigger: 'blur', message: '手机号不能为空' }
                    , { validator: checkMobile, trigger: 'blur' }]
            }
        }
    },
    created() {
        this.getUserListInfo()
    },
    methods: {
        async getUserListInfo() {
            const { data: res } = await this.$http.get('users', { params: this.queryInfo })
            if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
            this.userList = res.data.users
            this.total = res.data.total
        },
        handleSizeChange(newStr) {
            this.queryInfo.pagesize = newStr
            this.getUserListInfo()
        },
        handleCurrentChange(newCurrent) {
            this.queryInfo.pagenum = newCurrent
            this.getUserListInfo()
        },
        async userStateChanged(userInfo) {
            console.log(userInfo)
            const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if (res.meta.status !== 200) {
                return this.$message.error('用户状态更新失败')
            } else {
                return this.$message.success('用户状态更新成功')
            }
        },
        addUserInfo() {
            this.adddialogvisable = true
        },
        addDialogClose() {
            this.$refs.addFormRef.resetFields()
        },
        editDialogClose() {
            this.$refs.editFormRef.resetFields()
        },
        adddUser() {
            this.$refs.addFormRef.validate(async vaild => {
                if (!vaild) return
                const { data: res } = await this.$http.post('users', this.addForm)
                if (res.meta.status !== 201) {
                    this.$message.error('添加新用户失败')
                }
                this.$message.success('添加新用户成功')

                this.adddialogvisable = false
                this.getUserListInfo()
            })
        },
        async editUserInfo(id) {
            const { data: res } = await this.$http.get('users/' + id)
            if (res.meta.status !== 200) {
                this.$message.error('获取用户失败')
            }
            this.editForm = res.data
            this.editdialogvisable = true
        },
        editUser() {
            this.$refs.editFormRef.validate(async vaild => {
                if (!vaild) return
                const { data: res } = await this.$http.put('users/' + this.editForm.id, {
                    mobile: this.editForm.mobile,
                    email: this.editForm.email
                })
                if (res.meta.status !== 200) {
                    this.$message.error('修改用户失败')
                }
                this.editdialogvisable = false
                this.getUserListInfo()
                this.$message.success('修改用户成功')
            })
        },
        // 根据id删除用户
        async removeUserbyId(id) {
            console.log(id)
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            console.log(confirmResult)
            const {data: res} = await this.$http.delete('users/'+ id)
            if (res.meta.status !== 200) {
                    this.$message.error('删除用户失败')
                }
                this.$message.success('删除用户成功')

                this.getUserListInfo()
        }
    }
}
</script>